package com.dries.security.core.social.config;

import com.dries.security.core.properties.SecurityCoreProperties;
import com.dries.security.core.social.jdbc.JdbcSocialUsersConnectionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.social.config.annotation.EnableSocial;
import org.springframework.social.config.annotation.SocialConfigurerAdapter;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.ConnectionSignUp;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.social.security.SpringSocialConfigurer;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * @Description: 社交登录配置主类
 * @Author ZSY
 * @createTime 2020/9/15 17:42
 */
@Configuration
@EnableSocial
public class SocialCoreConfig extends SocialConfigurerAdapter {

    @Resource
    private DataSource dataSource;
    @Resource
    private SecurityCoreProperties coreProperties;
    @Autowired(required = false)
    private ConnectionSignUp connectionSignUp;
    @Autowired(required = false)
    private SocialAuthFilterPostProcessor socialAuthFilterPostProcessor;

    @Override
    public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {

        JdbcSocialUsersConnectionRepository repository = new JdbcSocialUsersConnectionRepository(dataSource, connectionFactoryLocator, Encryptors.noOpText());
        // 设置数据库表名前缀
        // jdbcUsersConnectionRepository.setTablePrefix("");
        // 自动注册
        if (connectionSignUp != null) {
            repository.setConnectionSignUp(connectionSignUp);
        }
        return repository;
    }

    /**
     * 社交登录配置类，供浏览器或app模块引入设计登录配置用。
     * @return
     */
    @Bean
    public SpringSocialConfigurer driesSocialConfigurer() {

        String filterProcessesUrl = coreProperties.getSocial().getFilterProcessesUrl();
        // 设置授权路径
        DriesSpringSocialConfig config = new DriesSpringSocialConfig(filterProcessesUrl);
        // 设置注册页面
        config.signupUrl(coreProperties.getBrowser().getRegisterPage());

        config.setSocialAuthFilterPostProcessor(socialAuthFilterPostProcessor);
        return config;
    }

    /**
     * 配置Social的工具类，可以获取用户信息
     * @param factoryLocator
     * @return
     */
    @Bean
    public ProviderSignInUtils providerSignInUtils(ConnectionFactoryLocator factoryLocator) {
        return  new ProviderSignInUtils(factoryLocator, getUsersConnectionRepository(factoryLocator));
    }

}
